package com.xzxy.xmlg_backend.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xzxy.xmlg_backend.entity.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@Tag(name = "验证码")
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/captcha")
    @Operation(summary = "获取验证码", description = "生成验证码图片和文本")
    public Result getCaptcha() throws IOException {

        // 生成文本验证码
        String capthaText = defaultKaptcha.createText();

        // 生成验证码图片
        BufferedImage bi = defaultKaptcha.createImage(capthaText);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageIO.write(bi, "jpg", baos);

        byte[] bytes = baos.toByteArray();

        // 转base64
        String base64Image = Base64.getEncoder().encodeToString(bytes);

        Map<String, Object> result = new HashMap<>();
        result.put("image", "data:image/jpeg;base64," + base64Image);
        result.put("code", capthaText);

        return Result.success(result);
    }
}
